package com.gz.steak.common.aspect;

import com.gz.steak.common.aspect.anotation.OperationLog;
import com.gz.steak.common.exception.BusinessException;
import com.gz.steak.utils.convert.ConvertUtil;
import com.gz.steak.common.web.result.Result;
import com.gz.steak.modules.system.pojo.dataobject.SysOperationLog;
import com.gz.steak.modules.system.service.SysOperationService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Author 刘牌
 * @Date 2020/3/28 0028 22:33
 * @Version 1.0
 */
@Component
@Aspect
public class OperationLogAspect {

    private final static Logger logger = LoggerFactory.getLogger(LoginLogAspect.class);

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private SysOperationService sysOperationService;

    @Pointcut("@annotation(operationLog)")
    public void operationLog(OperationLog operationLog){

    }

    @Around("operationLog(log)")
    public Object doOperationLog(ProceedingJoinPoint point , OperationLog log) throws Throwable {
        return point.proceed();
    }

    @AfterThrowing(pointcut = "operationLog(log)" , throwing = "ex")
    public void exception(OperationLog log , BusinessException ex){
        logger.info("ex  "+ex);
    }

    @AfterReturning(pointcut = "operationLog(log)" , returning = "s")
    public void success(OperationLog log , Result s){
        String username = (String) request.getSession().getAttribute("username");
        SysOperationLog sysOperationLog = new SysOperationLog();
        sysOperationLog.setIp(request.getRemoteAddr())
                .setUserName(username)
                .setOperation(log.value())
                .setTime(ConvertUtil.FormatDate(new Date()))
                .setStatus("成功");
        sysOperationService.save(sysOperationLog);
    }
}
